<?php if ($this->grab) :?>
<script type="text/javascript">

var containers;
var grabId = <?= $this->grab->id ?>;

function initialize()
{   
    containers = {
        "main" : $("#container_main"),
        "inital" : $("#container_initial_import"),
        "lootTables" : $("#container_loot_tables"),
        "items" : $("#container_items"),
    };
    
    //alert('init');
    
    refresh();
}

function refresh()
{
    containers.main.html("");
    containers.inital.html("");
    containers.lootTables.html("");
    containers.items.html("");
    
    containers.main.append($.create("div", {"class":"ajax_loader"}));
    containers.inital.append($.create("div", {"class":"ajax_loader"}));
    containers.lootTables.append($.create("div", {"class":"ajax_loader"}));
    containers.items.append($.create("div", {"class":"ajax_loader"}));
    
    performCallback(    
        '<?= $this->url(array('controller'=>'data-grabber', 'action'=>'get-grab-info')) ?>', 
        { 'grabId' :  grabId },
        function(data) {
            displayData(data);
        }
    ); 
}

function displayData(data)
{
    displayMainData(data);
    displayInitialData(data);
    displayLootTableData(data);
    displayItemData(data);
}

function displayMainData(data) 
{
    containers.main.html("");
    
    if (!data.initial.fetched) {
        $.create("p", {}, "Initial data has not been imported.").appendTo(containers.main);
        return;
    }
    
    if (data.lootTables.total == 0) {
        $.create("p", {}, "No loot tables has been grabbed yet.").appendTo(containers.main);
        return;
    }
    
    if (data.lootTables.total != data.lootTables.fetched) {
        $.create("p", {}, "Loot table import is not complete yet.").appendTo(containers.main);
        return;
    }
    
    if (data.items.total == 0) {
        $.create("p", {}, "No items ids has been imported yet.").appendTo(containers.main);
        return;
    }
    
    if (data.items.total != data.items.fetched) {
        $.create("p", {}, "Item import not yet complete.").appendTo(containers.main);
        return;
    }
    
    
    $.create("strong", {}, "All data has been downloaded. ").appendTo(containers.main);
    $.create("a", {href: '<?= $this->url(array('controller'=>'data-grabber', 'action'=>'transfer', 'grab' => $this->grab->id)) ?>'}, "Click here to transfer to database.").appendTo(containers.main);
}

function displayInitialData(data)
{
    containers.inital.html("");
    
    if (!data.initial.fetched) {
        var btnImport = $.create("div", {"class":"button_small"}, "Import").click( function() {
            callAndRefresh('<?= $this->url(array('controller'=>'data-grabber', 'action'=>'import-initial-data')) ?>', {"grabId" : grabId});
        });
        containers.inital.append($.create("p", {}, "Initial data has not been imported."));
        containers.inital.append(btnImport);
        
        return;
    }
    
    $.create("strong", {}, "Dungeons Imported").appendTo(containers.inital);
    var dungeonList = $.create("ul").appendTo(containers.inital);
    $.each( data.initial.dungeons, function(i, dungeon) {
        $.create("li",{},dungeon.name + ' -- (' + dungeon.plId + '/' +dungeon.blizzardId + ')').appendTo(dungeonList);
    });
    
    var bossCount = 0;
    $.each( data.initial.bosses, function(i, boss) {
        bossCount++;
    });
    
    $.create("strong", {}, "Bosses Imported").appendTo(containers.inital);
    $.create("p", {}, bossCount + " imported").appendTo(containers.inital);
    var btnClearImport = $.create("div", {"class":"button_small"}, "Clear Import").click( function() {
        callAndRefresh('<?= $this->url(array('controller'=>'data-grabber', 'action'=>'clear-initial-import')) ?>', {"grabId" : grabId});
    });
    
    containers.inital.append(btnClearImport);
}

function displayLootTableData(data)
{
    containers.lootTables.html("");
    
    if (data.lootTables.total == 0) {
        $.create("p", {}, "No loot tables in this grab yet.").appendTo(containers.lootTables);
        return;
    }
    
    if (data.lootTables.total == data.lootTables.fetched) {
        $.create("p", {}, "All " + data.lootTables.total + " loot tables has been fetched.").appendTo(containers.lootTables);
        return;
    }
    
    $.create("p", {}, "There are a total of " + data.lootTables.total + " loot tables in this import.").appendTo(containers.lootTables);
    $.create("p", {}, "Currently " + data.lootTables.fetched + " are downloaded.").appendTo(containers.lootTables);
    
    var btnStartFetch = $.create("div", {"class":"button_small"}, "Start Fetch").click( function() { 
        containers.lootTables.html("");
        var statusText = $.create("p", {}).appendTo(containers.lootTables);
        var ajaxLoader = $.create("div", {"class":"ajax_loader"}).appendTo(containers.lootTables);
        startFetchingLootTables(statusText);
    });
    
    btnStartFetch.appendTo(containers.lootTables);
}

function startFetchingLootTables(statusText)
{
    $.ajax({
        url: '<?= $this->url(array('controller'=>'data-grabber', 'action'=>'fetch-next-loot-table')) ?>',
        data: {"grabId" : grabId},
        async: false,
        type: 'POST',
        dataType: 'json',
        success: function(response) { 
            if (response.status != 200) {
                alert(response.message);
                refresh();
            } else {
                if (response.data.fetched == response.data.total) {
                    refresh();
                } else {
                    statusText.html(response.data.fetched + " out of " + response.data.total);
                    startFetchingLootTables(statusText);
                }
            }
        },
        error: function(response) { 
            alert("Error while fetching loot tables, no explanation for you.");
        }
    });
}

function displayItemData(data) 
{

    containers.items.html("");
    
    if (data.lootTables.total == 0) {
        $.create("p", {}, "No loot tables has been grabbed yet.").appendTo(containers.items);
        return;
    }
    
    if (data.lootTables.total != data.lootTables.fetched) {
        $.create("p", {}, "Loot table import is not complete yet.").appendTo(containers.items);
        return;
    }
    
    if (data.items.total == 0) {
        $.create("p", {}, "No items ids has been imported yet.").appendTo(containers.items);
        return;
    }
    
    $.create("p", {}, "There are a total of " + data.items.total + " items in this import.").appendTo(containers.items);
    $.create("p", {}, "Currently " + data.items.fetched + " are downloaded.").appendTo(containers.items);
    $.create("p", {}, "There were " + data.items.errors + " items not found on wowhead (ie. they havent dropped).").appendTo(containers.items);
    $.create("p", {}, "There were " + data.items.missingSlot + " items missing slots (ie. crafting, quest or uknown token items).").appendTo(containers.items);
    
    if (data.items.total == data.items.fetched) {
        $.create("strong", {}, "All items are imported.").appendTo(containers.items);
        return;
    }
    
    var btnStartFetch = $.create("div", {"class":"button_small"}, "Start Fetch").click( function() { 
        alert("This will take a while, go make a cup of coffee...");
        containers.items.html("");
        var statusText = $.create("p", {}).appendTo(containers.items);
        var ajaxLoader = $.create("div", {"class":"ajax_loader"}).appendTo(containers.items);
        startFetchingItems(statusText);
    });
    
    btnStartFetch.appendTo(containers.items);
}

function startFetchingItems(statusText)
{
    $.ajax({
        url: '<?= $this->url(array('controller'=>'data-grabber', 'action'=>'fetch-next-item')) ?>',
        data: {"grabId" : grabId},
        async: false,
        type: 'POST',
        dataType: 'json',
        success: function(response) { 
            if (response.status != 200) {
                alert(response.message);
                refresh();
            } else {
                if (response.data.fetched == response.data.total) {
                    refresh();
                } else {
                    statusText.html(response.data.fetched + " out of " + response.data.total + " (" + response.data.errors + " items not found on wowhead)");
                    //refresh();
                    startFetchingItems(statusText);
                }
            }
        },
        error: function(response) { 
            alert("Error while items, no explanation for you.");
        }
    });
}

function callAndRefresh(script, params) 
{
    performCallback(    
        script, 
        params,
        function(data) {
            self.refresh();
        }
    ); 
}

function performCallback(script, params, callbackFunction)
{
    $.post( 
        script,
        params,
        function(response) { 
            if (response.status != 200) {
                alert(response.message);
            } else {
                callbackFunction(response.data);
            }
        },
        'json'
    );
}

function performNonAsyncCallback(script, params, callbackFunction)
{

}

$(document).ready( function() {
    initialize();
});

</script>


<?= $this->partial('data-grabber/menu.phtml'); ?>

<div class="content-full">

    <h1><?= $this->img("/images/icons/INV_Bijou_Gold.jpg") ?> Showing grab: <?= $this->grab->name ?></h1>
    
    <p>Release: <?= ($this->grab->release ? $this->grab->release : "all") ?></p>
    <p>Only raids: <?= ($this->grab->isRaid ? "yes" : "no") ?></p>
    
    <div id="container_main">
    </div>
</div>

<div class="content-full">
    
    <h1>Inital import</h1>
    
    <div id="container_initial_import">
    </div>
</div>

<div class="content-full">    
    <h1>Loot Tables</h1>
    
    <div id="container_loot_tables">
    </div>

</div>

<div class="content-full">    
    <h1>Items</h1>
    
    <div id="container_items">
    </div>

</div>
<?php else: ?>
<p>Unknown grab.</p>
<?php endif;?>